// src/store/modules/upgrade.store.ts
import { defineStore } from "pinia";
import { store } from "@/store";
import {
  UPGRADE_API,
  UpgradeProgressResponse,
  StartUpgradePayload,
  StartUpgradeResponse,
  StartRollbackPayload,
  StartRollbackResponse,
  CreateBackupPayload,
  BackupResponse,
} from "@/api/hmi/upgrade.api";
import type { ProgramInfo } from "@/api/hmi/upgrade.api";

import { ref, computed } from "vue";
import { ElMessage } from "element-plus";

// 定义升级状态枚举
export enum UpgradeStatus {
  IDLE = "idle", // 空闲状态
  UPLOADING = "uploading", // 文件上传中
  UPGRADING = "upgrading", // 升级进行中
  ROLLING_BACK = "rolling_back", // 回滚进行中
  SUCCESS = "success", // 操作成功
  FAIL = "fail", // 操作失败
}

export const useUpgradeStore = defineStore("upgrade", () => {
  // 当前程序信息 (示例数据，实际应从后端获取或初始化)
  const currentProgramInfo = ref<ProgramInfo>({
    name: "ESP811-v1.0.0-1C2A8C89.bin",
    version: "1.0.0",
    uploadTime: "2024-06-25 10:00:00",
    crc: "1C2A8C89",
    path: "",
  });

  // 新程序信息
  const newProgramInfo = ref<ProgramInfo | null>(null);

  // 备份点列表相关状态
  const backupList = ref<string[]>([]);
  const selectedBackup = ref<string | null>(null);

  // 升级进度相关状态
  const upgradeProgressPercentage = ref<number>(0);
  const upgradeStatusDescription = ref<string>("等待操作...");
  const upgradeCurrentStatus = ref<UpgradeStatus>(UpgradeStatus.IDLE); // 记录当前操作状态
  const pollingIntervalId = ref<number | null>(null); // 用于存储定时器ID

  // Computed 属性，用于进度条显示
  const progressDisplay = computed(() => {
    return {
      showProgress:
        upgradeCurrentStatus.value !== UpgradeStatus.IDLE &&
        upgradeCurrentStatus.value !== UpgradeStatus.UPLOADING,
      percentage: upgradeProgressPercentage.value,
      description: upgradeStatusDescription.value,
      // 根据状态设置 ElProgress 的 status 属性
      status:
        upgradeCurrentStatus.value === UpgradeStatus.SUCCESS
          ? "success"
          : upgradeCurrentStatus.value === UpgradeStatus.FAIL
            ? "exception"
            : undefined,
    };
  });

  /**
   * 设置当前程序信息
   * @param info 程序信息
   */
  const setCurrentProgramInfo = (info: ProgramInfo) => {
    currentProgramInfo.value = info;
  };

  /**
   * 设置新程序信息
   * @param info 程序信息
   */
  const setNewProgramInfo = (info: ProgramInfo | null) => {
    newProgramInfo.value = info;
  };

  /**
   * 设置备份点列表
   * @param list 备份点列表
   */
  const setBackupList = (list: string[]) => {
    backupList.value = list;
  };

  /**
   * 设置选中的备份点
   * @param backup 备份点名称
   */
  const setSelectedBackup = (backup: string | null) => {
    selectedBackup.value = backup;
  };

  /**  */

  /**
   * 更新升级进度状态
   * @param percentage 进度百分比
   * @param description 状态描述
   * @param status 当前操作状态
   */
  const updateUpgradeProgress = (
    percentage: number,
    description: string,
    status: UpgradeStatus
  ) => {
    console.log("updateUpgradeProgress:", percentage, description, status);
    upgradeProgressPercentage.value = percentage;
    upgradeStatusDescription.value = description;
    upgradeCurrentStatus.value = status;
  };
  /**
   * 从 API 获取升级进度
   * @returns Promise<UpgradeProgressResponse | null>
   */
  // const fetchUpgradeProgress = async (): Promise<UpgradeProgressResponse | null> => {
  //   return new Promise(async (resolve, reject) => {
  //     try {
  //       const res = await UPGRADE_API.getUpgradeProgress();
  //       if (res.status === "ok") {
  //         // 根据返回的进度和描述更新Store状态
  //         if (res.data >= 100) {
  //           // 进度达到100%或以上，表示成功
  //           updateUpgradeProgress(100, res.status_des || "操作完成", UpgradeStatus.SUCCESS);
  //           stopPollingProgress(); // 进度达到100%，停止轮询
  //           ElMessage.success("操作已成功完成！");
  //         } else {
  //           // 如果当前状态是失败，则不更新为升级中
  //           if (upgradeCurrentStatus.value !== UpgradeStatus.FAIL) {
  //             updateUpgradeProgress(res.data, res.status_des, UpgradeStatus.UPGRADING);
  //           }
  //         }
  //         resolve(res);
  //       } else {
  //         // API 返回状态不是 'ok' 的情况
  //         updateUpgradeProgress(
  //           upgradeProgressPercentage.value,
  //           res.status_des || "操作状态异常",
  //           UpgradeStatus.FAIL
  //         );
  //         ElMessage.error(`获取操作进度失败: ${res.status_des}`);
  //         stopPollingProgress(); // 出错停止轮询
  //         reject(new Error(res.status_des || "API返回状态异常"));
  //       }
  //     } catch (error: any) {
  //       console.error("fetchUpgradeProgress error:", error);
  //       updateUpgradeProgress(upgradeProgressPercentage.value, "获取进度失败", UpgradeStatus.FAIL);
  //       ElMessage.error("获取操作进度失败，请检查网络或服务器！");
  //       stopPollingProgress(); // 出错停止轮询
  //       reject(error);
  //     }
  //   });
  // };

  /**
   * 从 API 获取备份点列表
   * @returns Promise<string[] | null>
   */
  const fetchBackupList = async (): Promise<string[] | null> => {
    return new Promise((resolve) => {
      UPGRADE_API.getBackupList()
        .then((res: string[]) => {
          console.log("fetchBackupList:", res);
          if (res && Array.isArray(res)) {
            setBackupList(res);
            resolve(res);
          } else {
            ElMessage.error("获取备份点列表失败：数据格式错误");
            resolve(null);
          }
        })
        .catch((error: any) => {
          console.error("fetchBackupList error:", error);
          ElMessage.error("获取备份点列表失败，请检查网络或服务器！");
          resolve(null);
        });
    });
  };

  /**
   * 从 API 获取升级进度
   * @returns Promise<UpgradeProgressResponse | null>
   */
  const fetchUpgradeProgress = async (): Promise<UpgradeProgressResponse | null> => {
    // 外部函数依然可以是 async，因为它返回一个 Promise，
    // 这样调用方仍然可以使用 await fetchUpgradeProgress() 的形式。
    // async 关键字会隐式地“解包”这个内部返回的 Promise。
    console.log("fetchUpgradeProgress ############################################");
    return new Promise((resolve) => {
      // 注意：这里移除了 async 关键字，并且只接收 resolve
      UPGRADE_API.getUpgradeProgress() // UPGRADE_API.getUpgradeProgress() 返回一个 Promise
        .then((res) => {
          console.log("fetchUpgradeProgress:", res, Number(res.progress));
          // API 调用成功，处理响应
          if (res.state === "ok") {
            // 根据返回的进度和描述更新Store状态
            if (Number(res.progress) >= 100) {
              // 进度达到100%或以上，表示成功
              updateUpgradeProgress(100, res.state_name || "操作完成", UpgradeStatus.SUCCESS);
              stopPollingProgress(); // 进度达到100%，停止轮询
              // ElMessage.success("操作已成功完成！");
            } else {
              // 如果当前状态是失败，则不更新为升级中
              if (upgradeCurrentStatus.value !== UpgradeStatus.FAIL) {
                updateUpgradeProgress(
                  Number(res.progress),
                  res.state_name,
                  UpgradeStatus.UPGRADING
                );
              }
            }
            resolve(res); // 操作成功，resolve 响应数据
          } else {
            // API 返回状态不是 'ok' 的情况
            updateUpgradeProgress(
              Number(res.progress),
              res.state_name || "操作状态异常",
              UpgradeStatus.FAIL
            );
            ElMessage.error(`获取操作进度失败: ${res.state_name}`);
            stopPollingProgress(); // 出错停止轮询
            resolve(null); // 操作失败，resolve null
          }
        })
        .catch((error: any) => {
          // API 调用失败，捕获异常
          console.error("fetchUpgradeProgress error:", error);
          updateUpgradeProgress(
            upgradeProgressPercentage.value,
            "获取进度失败",
            UpgradeStatus.FAIL
          );
          ElMessage.error("获取操作进度失败，请检查网络或服务器！");
          stopPollingProgress(); // 出错停止轮询
          resolve(null); // 捕获到异常，resolve null
        });
    });
  };

  /**
   * 开始轮询升级进度
   * @param interval 轮询间隔，默认为2秒
   */
  const startPollingProgress = (interval: number = 2000) => {
    if (pollingIntervalId.value !== null) {
      clearInterval(pollingIntervalId.value);
    }
    // 立即执行一次，然后每隔interval执行
    fetchUpgradeProgress();

    pollingIntervalId.value = window.setInterval(fetchUpgradeProgress, interval);
  };

  /**
   * 停止轮询升级进度
   */
  const stopPollingProgress = () => {
    if (pollingIntervalId.value !== null) {
      clearInterval(pollingIntervalId.value);
      pollingIntervalId.value = null;
    }
  };

  /**
   * 开始升级过程
   * @returns Promise<StartUpgradeResponse | null>
   */
  const startUpgradeProcess = async (): Promise<StartUpgradeResponse | null> => {
    if (!newProgramInfo.value) {
      ElMessage.warning("请先上传新程序文件！");
      return null;
    }
    if (
      upgradeCurrentStatus.value === UpgradeStatus.UPGRADING ||
      upgradeCurrentStatus.value === UpgradeStatus.ROLLING_BACK
    ) {
      ElMessage.warning("当前已有操作正在进行中，请勿重复操作！");
      return null;
    }

    return new Promise((resolve) => {
      updateUpgradeProgress(0, "正在启动升级...", UpgradeStatus.UPGRADING);
      const params: StartUpgradePayload = {
        filePath: newProgramInfo.value!.path,
      };

      UPGRADE_API.startUpgrade(params)
        .then((res: StartUpgradeResponse) => {
          if (res.success) {
            ElMessage.success(res.message || "升级任务已成功启动，正在获取进度...");
            setTimeout(() => {
              startPollingProgress();
            }, 1000);
            resolve(res);
          } else {
            updateUpgradeProgress(
              upgradeProgressPercentage.value,
              res.message || "升级启动失败",
              UpgradeStatus.FAIL
            );
            ElMessage.error(res.message || "升级任务启动失败！");
            resolve(null);
          }
        })
        .catch((error: any) => {
          console.error("startUpgradeProcess error:", error);
          updateUpgradeProgress(
            upgradeProgressPercentage.value,
            "升级启动异常",
            UpgradeStatus.FAIL
          );
          ElMessage.error("升级任务启动异常！");
          resolve(null);
        });
    });
  };

  /**
   * 开始回滚过程
   * @param backupName 备份点名称
   * @returns Promise<StartRollbackResponse | null>
   */
  const startRollbackProcess = async (
    backupName?: string
  ): Promise<StartRollbackResponse | null> => {
    if (
      upgradeCurrentStatus.value === UpgradeStatus.UPGRADING ||
      upgradeCurrentStatus.value === UpgradeStatus.ROLLING_BACK
    ) {
      ElMessage.warning("当前已有操作正在进行中，请勿重复操作！");
      return null;
    }

    return new Promise((resolve) => {
      updateUpgradeProgress(0, "正在启动回滚...", UpgradeStatus.ROLLING_BACK);
      const params: StartRollbackPayload = {
        backup_name: backupName || selectedBackup.value || "",
      };

      UPGRADE_API.startRollback(params)
        .then((res: StartRollbackResponse) => {
          if (res.success) {
            // ElMessage.success(res.message || "回滚任务已成功启动，正在获取进度...");
            startPollingProgress();
            newProgramInfo.value = null;
            resolve(res);
          } else {
            updateUpgradeProgress(
              upgradeProgressPercentage.value,
              res.message || "回滚启动失败",
              UpgradeStatus.FAIL
            );
            ElMessage.error(res.message || "回滚任务启动失败！");
            resolve(null);
          }
        })
        .catch((error: any) => {
          console.error("startRollbackProcess error:", error);
          updateUpgradeProgress(
            upgradeProgressPercentage.value,
            "回滚启动异常",
            UpgradeStatus.FAIL
          );
          ElMessage.error("回滚任务启动异常！");
          resolve(null);
        });
    });
  };

  /**
   * 重置升级状态到初始值
   */
  const resetUpgradeState = () => {
    stopPollingProgress(); // 停止所有轮询
    setNewProgramInfo(null);
    updateUpgradeProgress(0, "等待操作...", UpgradeStatus.IDLE);
    // currentProgramInfo 通常不需要重置，因为它代表设备当前状态
  };

  /**
   * 备份处理
   * @param filePath 文件路径
   * @returns Promise<BackupResponse | null>
   */
  const backupHandle = (filePath: string): Promise<BackupResponse | null> => {
    return new Promise((resolve) => {
      const params: CreateBackupPayload = {
        filePath: filePath,
      };

      UPGRADE_API.createBackup(params)
        .then((res: BackupResponse) => {
          if (res.success) {
            ElMessage.success(res.message || "备份成功！");
            resolve(res);
          } else {
            ElMessage.error(res.message || "备份失败！");
            resolve(null);
          }
        })
        .catch((error: any) => {
          console.error("backupHandle error:", error);
          ElMessage.error("备份处理异常！");
          resolve(null);
        });
    });
  };


  return {
    currentProgramInfo,
    newProgramInfo,
    backupList,
    selectedBackup,
    progressDisplay,
    upgradeCurrentStatus,
    setCurrentProgramInfo,
    setNewProgramInfo,
    setBackupList,
    setSelectedBackup,
    updateUpgradeProgress,
    fetchBackupList,
    fetchUpgradeProgress,
    startPollingProgress,
    stopPollingProgress,
    startUpgradeProcess,
    startRollbackProcess,
    resetUpgradeState,
    backupHandle,
  };
});

// 为了在非 setup 区域使用 store，导出此函数
export function useUpgradeStoreWithOutSetup() {
  return useUpgradeStore(store);
}
